var data = (function () {
    //"use strict";
	var DB, mainPage, addSum, takeSum, changeEndDate, savingsList, accountList, reservedList, saveSum, reserveSum, transferSum;

    mainPage = {

        getAccounts:function (action){
            accountList.getAccountList(action);
        }
    };
    
    transferSum = {
    	transferSum: function(data, action){
    		DB.db.transaction(
    			function(tx){
    				tx.executeSql("Select * from Accounts where AccountID = " + data.FromAccountID, [],
			    		function (tx, results) {
			    			if(results.rows.item(0).Sum < data.Sum){
			    				data.Sum = results.rows.item(0).Sum;
			    			}
			    			tx.executeSql("Update Accounts SET Sum=" + (results.rows.item(0).Sum - data.Sum) + " where AccountID = " + data.FromAccountID);
			    			tx.executeSql("Select * from Accounts where AccountID = " + data.ToAccountID, [],
					    		function (tx, results) {
					    			tx.executeSql("Update Accounts SET Sum=" + (results.rows.item(0).Sum + data.Sum) + " where AccountID = " + data.ToAccountID);
					    		}, DB.errorCB);
			    		}, DB.errorCB);
		    		}, DB.errorCB);
    	}
    };

    reservedList = {
        getReservedList: function (action) {
            DB.db.transaction(
                function (tx) {
                    tx.executeSql("SELECT * FROM Reserved", [],
                        function (tx, results) {
                            action(results);
                        }, DB.errorCB);
                }, DB.errorCB);
        },
        saveReserved: function (action, newData) {
            DB.db.transaction(
                function (tx) {
                    tx.executeSql("SELECT max(ReserveID) as ID FROM Reserved", [],
                        function (tx, results) {
                            var num;
                            if (results.rows.length !== 0) {
                                num = results.rows.item(0).ID;
                                tx.executeSql("INSERT INTO Reserved (ReserveID, Name, Sum) VALUES (" + (num + 1) + ", '" +
                                    newData.Name + "', " + newData.Sum + ")");
                            } else {
                                tx.executeSql("INSERT INTO Reserved (ReserveID, Name, Sum) VALUES (1 , '" +
                                    newData.Name + "', " + newData.Sum + ")");
                            }
                            action();
                        }, DB.errorCB);
                }, DB.errorCB);
        },
        editReserved: function (action, newData) {
            DB.db.transaction(
                function (tx) {
                    tx.executeSql("UPDATE Reserved SET Name='" + newData.Name + "' where ReserveID=" + newData.ReserveID);
                    action();
                }, DB.errorCB);
        },
        deleteReserved: function (reserveID, action){
            DB.db.transaction(
                function (tx) {
                    tx.executeSql("delete from Reserved where ReserveID = " + reserveID);
                    tx.executeSql("SELECT * FROM Reserved", [],
                        function (tx, results) {
                            action(results);
                        }, DB.errorCB);
                },
                DB.errorCB
            )
        }
    };

    savingsList = {
        getAccountList: function (action) {
            DB.db.transaction(
                function (tx) {
                    tx.executeSql("SELECT * FROM Savings", [],
                        function (tx, results) {
                            action(results);
                        }, DB.errorCB);
                }, DB.errorCB);
        },
        saveSaving: function (action, newData) {
            DB.db.transaction(
                function (tx) {
                    tx.executeSql("SELECT max(SavingID) as ID FROM Savings", [],
                        function (tx, results) {
                            var num;
                            if (results.rows.length !== 0) {
                                num = results.rows.item(0).ID;
                                tx.executeSql("INSERT INTO Savings (SavingID, Name, Sum) VALUES (" + (num + 1) + ", '" +
                                    newData.Name + "', " + newData.Sum + ")");
                            } else {
                                tx.executeSql("INSERT INTO Savings (SavingID, Name, Sum) VALUES (1 , '" +
                                    newData.Name + "', " + newData.Sum + ")");
                            }
                            action();
                        }, DB.errorCB);
                }, DB.errorCB);
        },
        editSaving: function (action, newData) {
            DB.db.transaction(
                function (tx) {
                    tx.executeSql("UPDATE Savings SET Name='" + newData.Name + "' where SavingID=" + newData.SavingID);
                    action();
                }, DB.errorCB);
        },
        deleteSaving: function (savingID, action){
            DB.db.transaction(
                function (tx) {
                    tx.executeSql("delete from Savings where SavingID = " + savingID);
                    tx.executeSql("SELECT * FROM Savings", [],
                        function (tx, results) {
                            action(results);
                        }, DB.errorCB);
                },
                DB.errorCB
            )
        }
    };

    accountList = {
        action: null,
        getAccountList: function (action) {
             DB.db.transaction(
                 function (tx) {
                    tx.executeSql("SELECT * FROM Accounts", [],
                     function (tx, results) {
                        action(results);   
                     }, DB.errorCB);   
                 }, DB.errorCB);
        },
        deleteAccount: function (accountID, action){
            DB.db.transaction(
                function (tx) {
                    tx.executeSql("delete from Accounts where AccountID = " + accountID);
                    tx.executeSql("SELECT * FROM Accounts", [],
                        function (tx, results) {
                            action(results);
                        }, DB.errorCB);
                },
                DB.errorCB
            )
        },
        getAccountListOrderBySum: function (action) {
            DB.db.transaction(
                function (tx) {
                    tx.executeSql("SELECT * FROM Accounts ORDER BY Sum DESC", [],
                        function (tx, results) {
                            action(results);
                        }, DB.errorCB);
                }, DB.errorCB);
        },
        saveAccount: function (action, newData) {
               DB.db.transaction(
                 function (tx) {
                    tx.executeSql("SELECT max(AccountID) as ID FROM Accounts", [],
                     function (tx, results) {
                        var num; 
                        if (results.rows.length !== 0) {
                            num = results.rows.item(0).ID;
                            tx.executeSql("INSERT INTO Accounts (AccountID, Name, Sum) VALUES (" + (num + 1) + ", '" +
                                newData.Name + "', " + newData.Sum + ")");
                        } else {
                            tx.executeSql("INSERT INTO Accounts (AccountID, Name, Sum) VALUES (1 , '" +
                                newData.Name + "', " + newData.Sum + ")");
                        }
                        action();
                     }, DB.errorCB);   
                 }, DB.errorCB);
        },
        editAccount: function (action, newData) {
            DB.db.transaction(
                function (tx) {
                    tx.executeSql("UPDATE Accounts SET Name='" + newData.Name + "' where AccountID=" + newData.AccountID);
                    action();
                }, DB.errorCB);
        }
    };

    chageEndDate = {
        data: null,
        getDates: function (action){
            DB.db.transaction(function (tx){
                tx.executeSql("SELECT StartDate, EndDate FROM CurrentState", [],
                function (tx, results){
                    action(results);
                })
            })
        },
        insertData: function (data) {
            chageEndDate.data = data;
            DB.db.transaction(chageEndDate.updateEndDate, DB.errorCB);
        },
        updateEndDate: function (tx) {
			tx.executeSql("UPDATE CurrentState SET EndDate = '" + chageEndDate.data.EndDate + "'");
			hdmain.updateData();
		}
    };

    reserveSum = {
        insertSum: function (data) {
            DB.db.transaction( function (tx){
            	var dateNow = new Date();
                tx.executeSql("Insert into ResarveSum (Sum, ReserveID, AddDate, sysdate) values (" + data.Sum + "," +
                    data.ReserveID + ",'" + (dateNow.getMonth()+1) + "/" + dateNow.getDate() + "/" + dateNow.getFullYear() + "'," +
                    dateNow.getFullYear() + ((dateNow.getDate() + 1) < 10 ? "0" + (dateNow.getMonth() + 1) : (dateNow.getMonth() + 1)) + (dateNow.getDate() < 10 ? "0" + dateNow.getDate() : dateNow.getDate()) + ")");
                tx.executeSql("select * from Reserved where ReserveID=" + data.ReserveID,[], function (tx, results){
                	tx.executeSql("update Reserved set Sum=" + (results.rows.item(0).Sum * 100 + data.Sum * 100 )/100 + " where ReserveID=" + data.ReserveID);
                })
            }, DB.errorCB);
        },
        getTodayReservedData: function (action){
			DB.db.transaction(function(tx){
					var dateNow = new Date();
					tx.executeSql("Select Sum(Sum) as Sum from ResarveSum where sysdate="  +
                    dateNow.getFullYear() + ((dateNow.getDate() + 1) < 10 ? "0" + (dateNow.getMonth() + 1) : (dateNow.getMonth() + 1)) + 
                    (dateNow.getDate() < 10 ? "0" + dateNow.getDate() : dateNow.getDate()),[],function (tx, results){
						action(results.rows);
				}, DB.errorCB)
			}, DB.errorCB)
		},
        getReservedSum: function( action ){
            DB.db.transaction(function(tx){
                tx.executeSql("Select Sum(Sum) as Sum from Reserved",[], function (tx, results){
                    if(results.rows.length !== 0){
                        action( results.rows.item(0).Sum );
                    }else{
                        action( 0 );
                    }
                })
            }, DB.errorCB)
        }
	};

	saveSum = {
		insertSum: function (data) {
			DB.db.transaction( function (tx){
                tx.executeSql("SELECT * FROM Accounts WHERE AccountID=" + data.AccountID, [],
                    function (tx, results) {
                        var sumToTake
                        if(results.rows.item(0).Sum < data.Sum){
                            data.Sum = results.rows.item(0).Sum;
                        }
                        tx.executeSql("UPDATE Accounts SET Sum = " + (results.rows.item(0).Sum - data.Sum) +
                            " WHERE AccountID=" + data.AccountID);
                        tx.executeSql("SELECT * FROM Savings WHERE SavingID=" + data.SavingID, [],
                        	function (tx, results) {
                        		tx.executeSql("UPDATE Savings SET Sum = " + (results.rows.item(0).Sum + data.Sum) +
                            " WHERE SavingID=" + data.SavingID);
                        	}, DB.errorCB);
                        var dateNow = new Date();
                        tx.executeSql("Insert into SaveSum (Sum, SavingID, AddDate, sysdate) values (" + data.Sum + "," + 
                    		data.SavingID + ",'" + (dateNow.getMonth()+1) + "/" + dateNow.getDate() + "/" + dateNow.getFullYear() + "'," +
                    		dateNow.getFullYear() + ((dateNow.getDate() + 1) < 10 ? "0" + (dateNow.getMonth() + 1) : (dateNow.getMonth() + 1)) + (dateNow.getDate() < 10 ? "0" + dateNow.getDate() : dateNow.getDate()) + ")");
                        tx.executeSql("SELECT * FROM CurrentState", [],
                            function (tx, results) {
                                var temp;
                                takeSum.sum = 0;
                                if (results.rows.length !== 0) {
                                    takeSum.sum = parseFloat(results.rows.item(0).Sum);
                                    temp = parseInt(takeSum.sum * 100, 10);
                                    takeSum.sum = temp / 100;
                                    temp = parseInt(data.Sum * 100, 10);
                                    data.Sum = temp / 100;
                                    tx.executeSql("UPDATE CurrentState SET Sum = " + (takeSum.sum - data.Sum));

                                    hdmain.updateData();
                                    hdcurrentstate.show();
                                }
                            }, DB.errorCB);
                    }, DB.errorCB);
            }, DB.errorCB);
		},
		getTodaySavedData: function (action){
			DB.db.transaction(function(tx){
					var dateNow = new Date();
					tx.executeSql("Select Sum(Sum) as Sum from SaveSum where sysdate="  +
                    dateNow.getFullYear() + ((dateNow.getDate() + 1) < 10 ? "0" + (dateNow.getMonth() + 1) : (dateNow.getMonth() + 1)) + 
                    (dateNow.getDate() < 10 ? "0" + dateNow.getDate() : dateNow.getDate()),[],function (tx, results){
						action(results.rows);
				}, DB.errorCB)
			}, DB.errorCB)
		}	
	};
	
    takeSum = {
        data: null,
        sum: null,
        insertData: function (data) {
            takeSum.data = data;
            DB.db.transaction( function (tx){
                tx.executeSql("SELECT * FROM Accounts WHERE AccountID=" + takeSum.data.AccountID, [],
                    function (tx, results) {
                        var sumToTake
                        if(results.rows.item(0).Sum < takeSum.data.Sum){
                            takeSum.data.Sum = results.rows.item(0).Sum;
                        }
                        tx.executeSql("UPDATE Accounts SET Sum = " + (results.rows.item(0).Sum - takeSum.data.Sum) +
                            " WHERE AccountID=" + takeSum.data.AccountID);
                        var dateNow = new Date();
                        tx.executeSql("Insert into TakeSum (Sum, AccountID, AddDate, sysdate) values (" + takeSum.data.Sum + "," + 
                    		takeSum.data.AccountID + ",'" + (dateNow.getMonth()+1) + "/" + dateNow.getDate() + "/" + dateNow.getFullYear() + "'," +
                    		dateNow.getFullYear() + ((dateNow.getDate() + 1) < 10 ? "0" + (dateNow.getMonth() + 1) : (dateNow.getMonth() + 1)) + (dateNow.getDate() < 10 ? "0" + dateNow.getDate() : dateNow.getDate()) + ")");
                        tx.executeSql("SELECT * FROM CurrentState", [],
                            function (tx, results) {
                                var temp;
                                takeSum.sum = 0;
                                if (results.rows.length !== 0) {
                                    takeSum.sum = parseFloat(results.rows.item(0).Sum);
                                    temp = parseInt(takeSum.sum * 100, 10);
                                    takeSum.sum = temp / 100;
                                    temp = parseInt(takeSum.data.Sum * 100, 10);
                                    takeSum.data.Sum = temp / 100;
                                    tx.executeSql("UPDATE CurrentState SET Sum = " + (takeSum.sum - takeSum.data.Sum));

                                    hdmain.updateData();
                                    hdcurrentstate.show();
                                }
                            }, DB.errorCB);
                    }, DB.errorCB);
            }, DB.errorCB);
        },
        getTodayTakenData: function (action){
			DB.db.transaction(function(tx){
					var dateNow = new Date();
					tx.executeSql("Select Sum(Sum) as Sum from TakeSum where sysdate="  +
                    dateNow.getFullYear() + ((dateNow.getDate() + 1) < 10 ? "0" + (dateNow.getMonth() + 1) : (dateNow.getMonth() + 1)) + 
                    (dateNow.getDate() < 10 ? "0" + dateNow.getDate() : dateNow.getDate()),[],function (tx, results){
						action(results.rows);
				}, DB.errorCB)
			}, DB.errorCB)
		}
    };
    
	addSum = {
		data: null,
		sum: null,
        saving: null,
		fun: null,
		getTodayAddedData: function (action){
			DB.db.transaction(function(tx){
					var dateNow = new Date();
					tx.executeSql("Select Sum(Sum) as Sum from AddingSum where sysdate="  +
                    dateNow.getFullYear() + ((dateNow.getDate() + 1) < 10 ? "0" + (dateNow.getMonth() + 1) : (dateNow.getMonth() + 1)) + 
                    (dateNow.getDate() < 10 ? "0" + dateNow.getDate() : dateNow.getDate()),[],function (tx, results){
						action(results.rows);
				}, DB.errorCB)
			}, DB.errorCB)
		},
		getInitData: function (fun) {
			addSum.fun = fun;
			DB.db.transaction(addSum.initData, DB.errorCB);
		},
		initData: function (tx) {
			tx.executeSql('SELECT * FROM CurrentState', [],
			addSum.getInitData_success, DB.errorCB);
		},
		getInitData_success: function (tx, results) {
			if (results.rows.length !== 0) {
				addSum.fun(results.rows);
			}
		},
		insertData: function (data) {
			addSum.data = data;
			DB.db.transaction(addSum.insertDataQuery, DB.errorCB);
		},
		insertDataQuery: function (tx) {
			tx.executeSql("SELECT * FROM CurrentState", [],
			addSum.insertDataQuery_success, DB.errorCB);
		},
		insertDataQuery_success: function (tx, results) {
			addSum.sum = 0;
            addSum.saving = 0;
			if (results.rows.length === 0) {
				DB.db.transaction(addSum.insertSum, DB.errorCB);
			} else {
				addSum.sum = parseFloat(results.rows.item(0).Sum);
                addSum.saving = parseFloat(results.rows.item(0).Saving);
				DB.db.transaction(addSum.updateSum, DB.errorCB);
			}
		},
		insertSum: function (tx) {
			tx.executeSql("INSERT INTO CurrentState (Sum, Saving, StartDate, EndDate) VALUES (" + addSum.data.Sum + ", 0, '','')");
            tx.executeSql("SELECT * FROM Accounts WHERE AccountID=" + addSum.data.AccountID, [],
                function (tx, results) {
                    tx.executeSql("UPDATE Accounts SET Sum = " + (results.rows.item(0).Sum + addSum.data.Sum) +
                        " WHERE AccountID=" + addSum.data.AccountID);
                    var dateNow = new Date();
                    tx.executeSql("Insert into AddingSum (Sum, AccountID, AddDate, sysdate) values (" + addSum.data.Sum + "," + 
                    addSum.data.AccountID + ",'" + (dateNow.getMonth()+1) + "/" + dateNow.getDate() + "/" + dateNow.getFullYear() + "'," +
                    dateNow.getFullYear() + ((dateNow.getDate() + 1) < 10 ? "0" + (dateNow.getMonth() + 1) : (dateNow.getMonth() + 1)) + (dateNow.getDate() < 10 ? "0" + dateNow.getDate() : dateNow.getDate()) + ")");
                    hdmain.updateData();
                    hdcurrentstate.show();
                }, DB.errorCB);
		},
		
		updateSum: function (tx) {
			var temp;
			temp = parseInt(addSum.sum * 100, 10);
			addSum.sum = temp / 100;
			temp = parseInt(addSum.data.Sum * 100, 10);
			addSum.data.Sum = temp / 100;

			tx.executeSql("UPDATE CurrentState SET Sum = " + (addSum.sum + addSum.data.Sum));
            if(addSum.data.TakeSaving){
                tx.executeSql("SELECT * FROM Savings WHERE SavingID=" + addSum.data.SavingID, [],
                    function (tx, results) {
                        if(results.rows.item(0).Sum < addSum.data.Sum){
                            addSum.data.Sum = results.rows.item(0).Sum;
                        }
                        tx.executeSql("UPDATE Savings SET Sum = " + (results.rows.item(0).Sum - addSum.data.Sum) +
                            " WHERE SavingID=" + addSum.data.SavingID);
                        var dateNow = new Date();
                        tx.executeSql("Insert into AddingSum (Sum, AccountID, AddDate, sysdate) values (" + addSum.data.Sum + "," +
                            addSum.data.AccountID + ",'" + (dateNow.getMonth()+1) + "/" + dateNow.getDate() + "/" + dateNow.getFullYear() + "'," +
                            dateNow.getFullYear() + ((dateNow.getDate() + 1) < 10 ? "0" + (dateNow.getMonth() + 1) : (dateNow.getMonth() + 1)) + (dateNow.getDate() < 10 ? "0" + dateNow.getDate() : dateNow.getDate()) + ")");
                        hdmain.updateData();
                        hdcurrentstate.show();
                    }, DB.errorCB);
            }else{
                tx.executeSql("SELECT * FROM Accounts WHERE AccountID=" + addSum.data.AccountID, [],
                    function (tx, results) {
                        tx.executeSql("UPDATE Accounts SET Sum = " + (results.rows.item(0).Sum + addSum.data.Sum) +
                            " WHERE AccountID=" + addSum.data.AccountID);
                            var dateNow = new Date();
                        tx.executeSql("Insert into AddingSum (Sum, AccountID, AddDate, sysdate) values (" + addSum.data.Sum + "," +
                        addSum.data.AccountID + ",'" + (dateNow.getMonth()+1) + "/" + dateNow.getDate() + "/" + dateNow.getFullYear() + "'," +
                        dateNow.getFullYear() + ((dateNow.getDate() + 1) < 10 ? "0" + (dateNow.getMonth() + 1) : (dateNow.getMonth() + 1)) + (dateNow.getDate() < 10 ? "0" + dateNow.getDate() : dateNow.getDate()) + ")");
                        hdmain.updateData();
                        hdcurrentstate.show();
                    }, DB.errorCB);
            }

		}
	};
	
	DB = {
		db: null,
		
		init: function () {
			DB.db = window.openDatabase("Database", "1.0", "HB", 200000);
			DB.db.transaction(DB.createTables, DB.errorCB, DB.successCB);
		},
		
		createTables: function (tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS CurrentState ( Sum DOUBLE, Saving DOUBLE, StartDate DATE, EndDate DATE)');
            tx.executeSql('CREATE TABLE IF NOT EXISTS Accounts ( AccountID INTEGER, Name TEXT, Sum DOUBLE)');
            tx.executeSql('CREATE TABLE IF NOT EXISTS Savings ( SavingID INTEGER, Name TEXT, Sum DOUBLE)');
            tx.executeSql('CREATE TABLE IF NOT EXISTS Reserved ( ReserveID INTEGER, Name TEXT, Sum DOUBLE)');
            tx.executeSql('CREATE Table If Not Exists AddingSum (Sum double, AccountID integer, AddDate date, sysdate integer)');
            tx.executeSql('CREATE Table If Not Exists TakeSum (Sum double, AccountID integer, AddDate date, sysdate integer)');
            tx.executeSql('CREATE Table If Not Exists SaveSum (Sum double, SavingID integer, AddDate date, sysdate integer)');
            tx.executeSql('CREATE Table If Not Exists ResarveSum (Sum double, ReserveID integer, AddDate date, sysdate integer)');
            tx.executeSql('Select * from CurrentState',[],function (tx, results){
            	if(results.rows.length === 0){
            		var year = (new Date()).getFullYear()
            		tx.executeSql('INSERT INTO CurrentState (Sum, Saving, StartDate, EndDate) VALUES (0,0,"01/01/"' + year +  ',"02/01/' + year +  '")');
            	}
            }, DB.errorCB);
		},
		errorCB: function (err) {
			//alert(err.code);
		},
		
		successCB: function () {
			 //DB.db.transaction(DB.queryDB, DB.errorCB);
		}
	};

    this.DBdata = DB;

	this.transferSum = function(data, action){
		transferSum.transferSum(data, action);
	};
    this.getReservedSum = function( action ){
        return reserveSum.getReservedSum( action );
    }
    
    this.getTodayReservedData = function(action){
    	reserveSum.getTodayReservedData(action);
    };
    
    this.getTodaySavedData = function(action){
    	saveSum.getTodaySavedData(action);
    };
    
    this.saveSum = function (data) {
    	saveSum.insertSum(data);
    };
    
    this.reserveSum = function (data) {
    	reserveSum.insertSum(data);
    };
    
    this.getTodayTakenData = function(action){
    	takeSum.getTodayTakenData(action);
    };
    
    this.getTodayAddedData = function(action){
    	addSum.getTodayAddedData(action);
    };
    this.getReservedList = function (action){
        reservedList.getReservedList(action);
    };
    this.saveReserved = function (action, newData) {
        reservedList.saveReserved(action, newData);
    };
    this.editReserved = function (action, newData) {
        reservedList.editReserved(action, newData);
    };
    this.deleteReserved = function (reserveID, action) {
        reservedList.deleteReserved(reserveID, action);
    };
    this.getSavingsList = function (action){
        savingsList.getAccountList(action);
    };
    this.saveSavings = function (action, newData) {
        savingsList.saveSaving(action, newData);
    };
    this.editSaving = function (action, newData) {
        savingsList.editSaving(action, newData);
    };
    this.deleteSaving = function (savingID, action) {
        savingsList.deleteSaving(savingID, action);
    };
    this.deleteAccount = function (accountID, action) {
        accountList.deleteAccount(accountID, action);
    };
    this.saveAccount = function (action, newData) {
        accountList.saveAccount(action, newData);
    };
    this.editAccount = function (action, newData) {
        accountList.editAccount(action, newData);
    };
    this.getAccountList = function (action) {
        accountList.getAccountList(action);  
    };
    this.getAccountListOrderBySum = function (action) {
        accountList.getAccountListOrderBySum(action);
    };
    this.changeNewEndDate = function (data) {
        chageEndDate.insertData(data);
    };
    this.takeNewSum = function (data) {
        takeSum.insertData(data);
    };
	this.addNewSum = function (data) {
		addSum.insertData(data);
	};
	this.getSumState = function (fun) {
		addSum.getInitData(fun);
	};
	this.init = function () {
		DB.init();
	};
	this.init();
	return this;
}(data || {}));